package com.qf.utils;

import com.qf.bean.Employee;
import com.qf.bean.Menu;
import com.qf.bean.Role;
import com.qf.dao.EmployeeDao;
import com.qf.dao.MenuMapper;
import com.qf.dao.RoleMapper;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import sun.dc.pr.PRError;

import java.util.ArrayList;
import java.util.List;

/**
 * 26/11/2019
 * Echo
 * qmxc
 * Alibaba
 */
public class MyRealm extends AuthorizingRealm {
    @Autowired
    private MenuMapper menuMapper;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        Employee employee = (Employee)principalCollection.getPrimaryPrincipal();
        Role role = employee.getRole();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addRole(role.getRname());
        List<Menu> perssionList = menuMapper.findByRoleId2(role.getRoleid());
        ArrayList list = new ArrayList();
        for (Menu menu : perssionList) {
            System.out.println(menu.getPercode());
            list.add(menu.getPercode());
        }
        info.addStringPermissions(list);
        return info;
    }

    @Autowired
    private EmployeeDao employeeDao;
    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String username= (String)authenticationToken.getPrincipal();
        Employee employee = employeeDao.login(username);
        if (employee==null){
            System.out.println("认证结束1");
            return null;
        }else{
            SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(employee, employee.getLoginpassword(), ByteSource.Util.bytes(employee.getSalt()), "myrealm");
            return info;
        }
    }
}
